<?php
class Sales_Refund extends QDB_ActiveRecord_Abstract
{
	/**
	 * 返回对象的定义
	 *
	 * @static
	 *
	 * @return array
	 */
	static function __define()
	{
		return array
		(
			// 指定该 ActiveRecord 要使用的行为插件
			'behaviors' => '',

			// 指定行为插件的配置
			'behaviors_settings' => array
			(
			    # '插件名' => array('选项' => 设置),
			),

			// 用什么数据表保存对象
			'table_name' => 'sales_refund',

			// 指定数据表记录字段与对象属性之间的映射关系
			// 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
			'props' => array
			(
				// 主键应该是只读，确保领域对象的“不变量”
				'id' => array('readonly' => true),

				/**
				 *  可以在此添加其他属性的设置
				 */
				# 'other_prop' => array('readonly' => true),

				/**
				 * 添加对象间的关联
				 */
				# 'other' => array('has_one' => 'Class'),

			),

			/**
			 * 允许使用 mass-assignment 方式赋值的属性
			 *
			 * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
			 */
			'attr_accessible' => '',

			/**
			 * 拒绝使用 mass-assignment 方式赋值的属性
			 */
			'attr_protected' => 'id',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
			 *
			 * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
			 */
			'create_reject' => '',

			/**
			 * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
			 */
			'update_reject' => '',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
			 * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
			 *
			 * 如果填充值为一个数组，则假定为 callback 方法。
			 */
			'create_autofill' => array
			(
				# 属性名 => 填充值
				# 'is_locked' => 0,
			),

			/**
			 * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 填充值的指定规则同 create_autofill
			 */
			'update_autofill' => array
			(
			),

			/**
			 * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
			 *
			 * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
			 *
			 * 如果需要添加一个自定义验证，应该写成
			 *
			 * 'title' => array(
			 *	array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
			 * )
			 *
			 * 然后在该类中添加 checkTitle() 方法。函数原型如下：
			 *
			 * static function checkTitle($title)
			 *
			 * 该方法返回 true 表示通过验证。
			 */
			'validations' => array
			(
			),
		);
	}


/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

	/**
	 * 开启一个查询，查找符合条件的对象或对象集合
	 *
	 * @static
	 *
	 * @return QDB_Select
	 */
	static function find()
	{
		$args = func_get_args();
		return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
	}

	/**
	 * 返回当前 ActiveRecord 类的元数据对象
	 *
	 * @static
	 *
	 * @return QDB_ActiveRecord_Meta
	 */
	static function meta()
	{
		return QDB_ActiveRecord_Meta::instance(__CLASS__);
	}


/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */
	
	static function create($sales_order_id, $refund)
	{
		$judge_result = Sales_Order::judgeRefund($sales_order_id);
		if ($judge_result['ack'] == SUCCESS)
		{
			$sales_order = Sales_Order::find('id=?', $sales_order_id)->asArray()->getOne();
//			if ($sales_order['amount'] >= $sales_order['amount'] + $refund['type'] * $refund['refund_amount'])
			if (1)
			{
				$sales_refund = new Sales_Refund();
				$sales_refund->sales_order_id = $sales_order_id;
				$sales_refund->type = $refund['type'];
				$sales_refund->make_time = CURRENT_DATETIME;
				$sales_refund->make_user_id = CURRENT_USER_ID;
				$sales_refund->refund_method = $refund['refund_method'];
				$sales_refund->refund_amount = $refund['refund_amount'];
				$sales_refund->refund_account = $refund['refund_account'];
				$sales_refund->reason = $refund['reason'];
				$sales_refund->categories_name = $refund['categories_name'];
				$sales_refund->receive_transaction_id = $refund['receive_transaction_id'];
				$sales_refund->notes = $refund['notes'];
				$sales_refund->save();
				$refund_id = mysql_insert_id();
				return array('ack' => SUCCESS, 'message' => '', 'refund_id' => $refund_id);
			}
			else
			{
				return array('ack' => FAILURE, 'message' => 'refund amount is exceed');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}

	static function edit($sales_refund)
	{
		$judge_result = Sales_Refund::judgeEdit($sales_refund['id']);
		if ($judge_result['ack'] == SUCCESS)
		{
			$refund = Sales_Refund::find('id=?', $sales_refund['id'])->getOne();
			$refund->type = $sales_refund['type'];
			$refund->refund_amount = $sales_refund['refund_amount'];
			$refund->refund_account = $sales_refund['refund_account'];
			$refund->receive_transaction_id = $sales_refund['receive_transaction_id'];
			$refund->refund_method = $sales_refund['refund_method'];
			$refund->categories_name = $sales_refund['categories_name'];
			$refund->reason = $sales_refund['reason'];
			$refund->notes = $sales_refund['notes'];
			$refund->save();
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}
	
	static function delete($sales_refund_id)
	{
		$judge_result = Sales_refund::judgeDelete($sales_refund_id);
		if ($judge_result['ack'] == SUCCESS)
		{
			Sales_Refund::meta()->deleteWhere('id=?', $sales_refund_id);
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}

	static function judgeDelete($sales_refund_id)
	{
		$sales_refund = Sales_refund::find('id=?', $sales_refund_id)->asArray()->getOne();
		if ($sales_refund)
		{
			if ($sales_refund['status'] == Q::ini('custom_flag/sales_refund_status/new/value'))
			{
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' => 'sales refund is audited');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'sales refund is not exists');
		}
	}
	
	static function judgeEdit($sales_refund_id)
	{
		$sales_refund = Sales_Refund::find('id=?', $sales_refund_id)->asArray()->getOne();
		if ($sales_refund)
		{
			if ($sales_refund['status'] == Q::ini('custom_flag/sales_refund_status/new/value'))
			{
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' => 'sales refund status is incorrect');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'sales refund is not exists');
		}
	}

	/**
	 * 销售退款订单财务审核
	 * @param 销售退款订单ids $sales_refund_ids
	 * @param 退款信息refund $refund
	 */
	static function auditRefundFinance($sales_refund_ids, $refund)
	{
		$message = array();
		foreach ($sales_refund_ids as $key => $id)
		{
			$judge_result = Sales_Refund::judgeRefundAuditFinance($id);
			if ($judge_result['ack'] == SUCCESS)
			{
				$sales_refund = Sales_Refund::find('id=?', $id)->getOne();
				$sales_refund->refund_transaction_id = $refund['refund_transaction_id'];
				$sales_refund->refund_user_id = CURRENT_USER_ID;
				$sales_refund->refund_time = $refund['refund_time'];
				$sales_refund->audit_time = CURRENT_DATETIME;
				$sales_refund->status = Q::ini('custom_flag/sales_refund_status/audited/value');
				$sales_refund->save();
			}
			else
			{
				$message[] = 'No.' . ($key + 1) . ' ' . $judge_result['message'];
			}
		}
		if ($message)
		{
			return array('ack' => FAILURE, 'message' => implode(',', $message));
		}
		else
		{
			return array('ack' => SUCCESS, 'message' => '');
		}
	}
	
	static function judgeRefundAuditFinance($sales_refund_id)
	{
		$sales_refund = Sales_Refund::find('id=?', $sales_refund_id)->getOne();
		if ($sales_refund['id'])
		{
			if ($sales_refund['status'] == Q::ini('custom_flag/sales_refund_status/new/value'))
			{
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' => 'refund has already handled');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'sales refund order is not exists');
		}
	}
		
	
	static function search($condition, $cp, $ps)
	{
		$columns = array(
				'sales_order.*',
				'sales_refund.*',
				'shop.name as shop_name',
				'currency.code as currency_code, currency.symbol as currency_symbol'
		);
		$where = Sales_Refund::buildSearchWhere($condition);
		if ($cp == 0 && $ps == 0)
		{
			$select = Sales_Refund::find($where)
				->joinLeft('sales_order', '', 'sales_refund.sales_order_id=sales_order.id')
				->joinLeft('shop', '', 'shop.id=sales_order.shop_id')
				->joinLeft('currency', '', 'currency.id=sales_order.currency_id')
				->order('sales_refund.refund_time desc')->setColumns($columns);
			$pagination = array();
		}
		else
		{
			$select = Sales_Refund::find($where)
				->joinLeft('sales_order', '', 'sales_refund.sales_order_id=sales_order.id')
				->joinLeft('shop', '', 'shop.id=sales_order.shop_id')
				->joinLeft('currency', '', 'currency.id=sales_order.currency_id')
				->order('sales_refund.id desc')->setColumns($columns)->limitPage($cp, $ps);
			$pagination = $select->getPagination();
		}
		$sales_refund = $select->asArray()->getAll();
		return array(
				'ack' => SUCCESS,
				'message' => '',
				'data' => $sales_refund,
				'pagination' => $pagination
		);
	}
	
	static function buildSearchWhere($condition)
	{
		$where = '1';
		if (isset($condition['shop_user_mapping']))
		{
			$where .= ' and sales_order.shop_id in (\'' . implode('\',\'', $condition['shop_user_mapping']) . '\')';
		}
		if ( ! empty($condition['begin_refund_time']))
		{
			$where .= ' and sales_refund.refund_time>=\'' . $condition['begin_refund_time'] . '\'';
		}
		if ( ! empty($condition['end_refund_time']))
		{
			$where .= ' and sales_refund.refund_time<=\''.$condition['end_refund_time'].' 23:59:59\'';
		}
		if ( ! empty($condition['shop_id']))
		{
			if (is_array($condition['shop_id']))
			{
				$shop = implode(',', $condition['shop_id']);
				$where .= " and sales_order.shop_id in ({$shop})";
			}
			else
			{
				$where .= ' and sales_order.shop_id=\'' . $condition['shop_id'] . '\'';
			}
		}
		if ( ! empty($condition['number']))
		{
			$where .= ' and sales_order.number =\''.$condition['number'].'\'';
		}
		if ( ! empty($condition['refund_transaction_id']))
		{
			$where .= ' and sales_refund.refund_transaction_id =\''.$condition['refund_transaction_id'].'\'';
		}
		if ( ! empty($condition['reason']))
		{
			$where .= ' and sales_refund.reason =\''.$condition['reason'].'\'';
		}
		if ( ! empty($condition['refund_status']))
		{
			$refund_status_filter = '0';
			foreach (Q::ini('custom_flag/sales_refund_status') as $srs)
			{
				if (isset($condition['refund_status'][$srs['value']]) && $condition['refund_status'][$srs['value']] == $srs['value'])
				{
					$refund_status_filter .= ' or sales_refund.status=' . $srs['value'];
				}
			}
			$where .= ' and (' . $refund_status_filter . ')';
		}
		if ( ! empty($condition['shipping_status']))
		{
			$shipping_status_filter = '0';
			foreach (Q::ini('custom_flag/sales_order_shipping_status') as $srs)
			{
				if (isset($condition['shipping_status'][$srs['value']]) && $condition['shipping_status'][$srs['value']] == $srs['value'])
				{
					$shipping_status_filter .= ' or sales_order.shipping_status=' . $srs['value'];
				}
			}
			$where .= ' and (' . $shipping_status_filter . ')';
		}
		if ( ! empty($condition['type']))
		{
			$where .= ' and sales_refund.type=\'' . $condition['type'] . '\'';
		}
		return $where;
	}
	
	static function getSalesRefund(&$sales_order)
	{
		foreach ($sales_order as &$so)
		{
			$sales_refund = Sales_Refund::find('sales_refund.sales_order_id=?', $so['id'])->asArray()->getAll();
			$so['sales_refund'] = $sales_refund;
			$so['has_sales_refund'] = $sales_refund ? true : false;
		}
		unset($so);
	}
	
	static function editSalesRefundInfo($sales_refund)
	{
		$message = array();
		foreach ($sales_refund as $key => $val)
		{
			if (! empty($val))
			{
				$refund_info = Q::normalize($val, "\n");
				foreach ($refund_info as $ri)
				{
					if ( ! empty($ri))
					{
						$$key = Q::normalize($ri, ',');
						$refund = Sales_Refund::find('id=?', trim(${$key}[0]))->getOne();
						if ($refund['id'])
						{
							if ($key == 'refund_amount')
							{
								$refund->type = (trim(${$key}[1])>0) ? 1 : -1;
								$refund->$key = abs(trim(${$key}[1]));
								$refund->save();
							}
							elseif ($key == 'refund_transaction_id')
							{
								$refund->$key = trim(${$key}[1]);
								$refund->save();
							}
							if ($key == 'refund_delete_id')
							{
								$result = Sales_Refund::delete($refund['id']);
								if ($result['ack'] == FAILURE)
								{
									$message[$key]['failure'][] = 'refund_ID:' . $refund['id'] . ',' . $result['message'];
								}
								else
								{
									$message[$key]['success'][] = $refund['id'] . ' 删除成功';
								}
							}
							else
							{
								$message[$key]['success'][] = ${$key}[0] . ',' . ${$key}[1] . ' 修改成功';
							}
						}
						else
						{
							if (isset(${$key}[1]))
							{
								$message[$key]['failure'][] = ${$key}[0] . ',' . ${$key}[1] . ' 修改失败';
							}
							else
							{
								$message[$key]['failure'][] = ${$key}[0] . ' 删除失败';
							}
						}
					}
				}
			}
		}
		if (! empty($message))
		{
			return array('ack' => PARTIAL_FAILURE, 'message' => $message);
		}
		else
		{
			return array('ack' => SUCCESS, 'message' => '');
		}
	}
}